package logic

import (
	"context"
	"errors"
	"video-guard/models/cache"
	"video-guard/models/mysql"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *videorpc.UpdatePasswordRequest) (*videorpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.UserInfo
	err := user.FindUserById(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("未登录")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.PhoneNum).Result()
	if result == "" {
		return nil, errors.New("未发送短信")
	}

	if in.SendSms != result {
		return nil, errors.New("短信错误")
	}
	if in.NewPassword != in.AckPassword {
		return nil, errors.New("两次密码不一样")
	}
	user.Password = in.AckPassword
	err = user.UpdatePassword(mysql.DB)
	if err != nil {
		return nil, errors.New("修改失败")
	}
	return &videorpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
